<?php
class JddjApiModel
{
    public $chnId;
    public $syncCnt; //批量同步数量

    public function __construct(){
        $this->chnId = 3;
        $this->syncCnt = 100;
    }
    /*
        添加店铺信息
        params
            store_id 药店id
            storeName 门店名称
            start_time 开始时间
            end_time 结束时间
    */
    public function createStore($store_id = 0, $storeName = '', $start_time = '', $end_time = '')
    {
        $storeInfo = $this->getStoreInfoById($store_id); //获取药店信息

        if(empty($storeInfo)){
            $res = array(
                "errNo" => "1001"
            );
            return $res;
        }
        $start_time  =  $start_time + strtotime('00:00:00');
        $end_time  =  $end_time + strtotime('00:00:00');
        $point =  getPointLocation($storeInfo['JinDuX'], $storeInfo['WeiDuY']);

        $operator = $storeInfo['Contact']; //操作人
        $address = $storeInfo['Address']; //门店地址
        $longitude = $point['lng']; //门店经度
        $latitude = $point['lat']; //门店纬度
        $phone = $storeInfo['Tel'];  // 客服电话号码 

        $city = 1;
        $county = 220;

        $JddjStoreSvc = new JddjStoreSvc();

        $addStoreInfoData = $JddjStoreSvc->createStore($storeName, $phone, $city, $county, $address, $operator, $start_time, $end_time, $latitude, $longitude);

        $res = $JddjStoreSvc->sendCreateStore($addStoreInfoData);
        $res = json_decode($res, true);

        if($res['code'] === '0'){
            $other_shop_id = $res['result'];

            $addStore = $this->addChannelStoreInfo(
                $this->chnId, $store_id, $other_shop_id,
                $storeName, $storeInfo['Memo'],
                $start_time, $end_time,
                1
            );

            return $addStore;
        }else{
            $res = array(
                "errNo" => "2001",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        添加第三方店铺信息
        params
            channel_id 第三方渠道id
            store_id 快方药店id
            shop_id 第三方店铺id
            shop_name 第三方店铺名称
            shop_desc 第三方店铺描述
            start_time 营业开始时间
            end_time 营业结束时间
            store_status 店铺状态
    */
    public function addChannelStoreInfo(
        $channel_id = 0, $store_id = 0, $shop_id = 0, 
        $shop_name = "", $shop_desc = "", 
        $start_time = 0, $end_time = 0,
        $store_status = 0
    ){
        $ChannelStoreModel = new ChannelStoreModel();

        $res = $ChannelStoreModel->addChannelStoreInfo(
            $channel_id, $store_id, $shop_id, 
            $shop_name, $shop_desc, 
            $start_time, $end_time,
            $store_status
        );

        return $res;
    }

    /*
        修改店铺信息
        params
            chn_id 渠道id
            store_id 店铺id
            other_shop_name 第三方药店名称
            other_shop_desc 第三方药店广告
            start_time 营业开始时间
            end_time 营业结束时间
            shipping_fee 配送费
            store_status 店铺状态
    */
    public function updateStoreInfo($chn_id = 0, $store_id = 0, $other_shop_name = '', $other_shop_desc = '', $start_time = '', $end_time = '', $shipping_fee = 0, $store_status = 0)
    {
        $storeInfo = $this->getStoreInfoById($store_id); //获取药店信息

        if(empty($storeInfo)){
            $res = array(
                "errNo" => "1001"
            );
            return $res;
        }

        $otherShopInfo = getChannelStoreInfo($this->chnId, $store_id);//获取第三方门店ID
        $other_shop_id = $otherShopInfo['other_shop_id'];

        $shipping_start_time  =  strtotime($start_time);
        $shipping_end_time  =  strtotime($end_time);

        $shipping_time = date('H:i',$shipping_start_time).'-'.date('H:i',$shipping_end_time);  // 门店营业时间 

        if($store_status == '0')
        {
            $isOpen = 0;  //门店的营业状态 ： 1营业 0不营业  
        }elseif ($store_status == 1) {
            $isOpen = 1; 
        }elseif ($store_status == 2) {
            $isOpen = 0; 
        }  

        $JddjStoreSvc = new JddjStoreSvc();

        $data = $JddjStoreSvc->updateStoreInfo4Open($other_shop_id, $other_shop_name, $other_shop_desc, $shipping_time, $shipping_fee, $isOpen);
        $res = $JddjStoreSvc->sendUpdateStoreInfo4Open($data);
        var_dump($res);die;

        if($res['error'] == null){
            $location_start_time = strtotime($start_time) - strtotime('00:00:00');
            $location_end_time = strtotime($end_time) - strtotime('00:00:00');

            $updateStore = updateChannelStoreInfo($chn_id, $store_id, $other_shop_name, $other_shop_desc, $location_start_time, $location_end_time, $shipping_fee, $store_status);
            return $updateStore;
        }else{
            $res = array(
                "errNo" => "2001",
                "data" => $res
            );
            return $res;
        }
    }


    /*
        获取门店ID
    */
    public function getIds()
    {
        $MtStoreSvc = new MtStoreSvc();

        $data = $MtStoreSvc->getIds();
        $res = $MtStoreSvc->sendGetIds($data);

        if(empty($res['data']) == false){
            return $res['data'];
        }else{
            $res = array(
                "errNo" => "2008",
                "data" => $res
            );
            return $res;
        }

    }

    /*
        批量获取门店详细信息
        app_poi_codes 店铺ID list
    */
    public function mget($app_poi_codes = '')
    {
        $MtStoreSvc = new MtStoreSvc();

        $data = $MtStoreSvc->mget($app_poi_codes);
        $res = $MtStoreSvc->sendMget($data);

        if(empty($res['data']) == false){
            return $res['data'];
        }else{
            $res = array(
                "errNo" => "2009",
                "data" => $res
            );
            return $res;
        }

    }

    /*
        门店设置为营业状态
        params
            store_id 店铺id
    */
    public function openShop($store_id = 0)
    {
        $MtStoreSvc = new MtStoreSvc();

        $online_data = $MtStoreSvc->online($store_id);
        $online_res = $MtStoreSvc->sendOnline($online_data);

        $data = $MtStoreSvc->open($store_id);
        $res = $MtStoreSvc->sendOpen($data);

        if($res['errno'] == "0"){
            $open = updateChannelStoreStatus($this->chnId, $store_id, 1);

            return $open;
        }else{
            $res = array(
                "errNo" => "2006",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        商户停业
        params
            store_id 店铺id
    */
    public function closeShop($store_id = 0)
    {
        $MtStoreSvc = new MtStoreSvc();

        $data = $MtStoreSvc->close($store_id);
        $res = $MtStoreSvc->sendClose($data);

        if($res['errno'] == "0"){
            $close = updateChannelStoreStatus($this->chnId, $store_id, 0);

            return $close;
        }else{
            $res = array(
                "errNo" => "2006",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        门店下线
        params
            store_id 店铺id
    */
    public function offlineShop($store_id = 0)
    {
        $MtStoreSvc = new MtStoreSvc();

        $data = $MtStoreSvc->offline($store_id);
        $res = $MtStoreSvc->sendOffline($data);

        if($res['errno'] == "0"){
            $offline = updateChannelStoreStatus($this->chnId, $store_id, 2);

            return $close;
        }else{
            $res = array(
                "errNo" => "2006",
                "data" => $res
            );
            return $res;
        }
    }


    /*
        更新店铺公告
        params
            store_id 店铺id
            topic 公告信息
    */
    public function setShopTopic($store_id = 0, $topic = '')
    {
        $MtStoreSvc = new MtStoreSvc();

        $data = $MtStoreSvc->updatepromoteinfo($store_id, $topic);

        $res = $MtStoreSvc->sendUpdatepromoteinfo($data);

        if($res['errno'] == "0"){
            $save = updateChannelStoreTopic($this->chnId, $store_id, $topic);

            return $save;
        }else{
            $res = array(
                "errNo" => "2007",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        设置营业时间
        params
            store_id 店铺ID
            start_time 开始时间 秒数
            end_time 结束时间 秒数
    */
    public function setBusinessTime($store_id = 0, $start_time = 0, $end_time = 0)
    {
        $start_time = date("H:i", $start_time + strtotime('00:00:00'));
        $end_time = date("H:i", $end_time + strtotime('00:00:00'));
        $shipping_time = $start_time.'-'.$end_time;

        $MtStoreSvc = new MtStoreSvc();

        $data = $MtStoreSvc->updateShippingtime($store_id, $shipping_time);
        $businessTime = $MtStoreSvc->sendUpdateShippingtime($data);

        return $businessTime;
    }

    /*
        创建/更新门店配送范围
        params
            store_id 店铺ID
            start_time 开始时间 秒数
            end_time 结束时间 秒数
    */
    public function saveShipping($app_poi_code = 0, $app_shipping_code = 0, $type = 0, $min_price = 0)
    {
        $storeInfo = $this->getStoreInfoById($app_poi_code); //获取药店信息

        $StoreModel = new StoreModel();
        $area =  $StoreModel->getAreaPointByAreaId($storeInfo['AID']);

        $arr = array();
        foreach ($area as $key => $val) {
            $arr[] = array(
                "x" => intval($val['WeiDuY'] * pow(10,6)),
                "y" => intval($val['JinDuX'] * pow(10,6))
            );

        }
        $area = json_encode($arr);

        $MtStoreSvc = new MtStoreSvc();

        $data = $MtStoreSvc->saveShipping($app_poi_code, $app_shipping_code, $type, $area, $min_price);
        $res = $MtStoreSvc->sendSaveShipping($data);

        return $res;
    }

    /*
        获取门店配送范围
        params
            store_id 店铺ID
    */
    public function shippingList($app_poi_code = 0)
    {
        $MtStoreSvc = new MtStoreSvc();

        $data = $MtStoreSvc->shippingList($app_poi_code);
        $res = $MtStoreSvc->sendShippingList($data);
        
        return $res;
    }

    /*
        获取药店信息
        params
            store_id 药店id
    */
    public function getStoreInfoById($store_id = 0)
    {
        $StoreModel = new StoreModel();

        return $StoreModel->getStoreInfoById($store_id);
    }

    /*
        初始化自定义分类
        params
            store_id 店铺id
    */
    public function initCategoryInfo($store_id = '')
    {
        $defaultCategory = $GLOBALS['defaultCategory'];

        foreach ($defaultCategory as $key => $value) {
            $this->addShopCategory(0, $key, $store_id, $value);
        }

        return true;
    }

    /*
        添加商品分类
        params
            pid    Int  是   父分类ID
            category_id    Int  是  商品分类ID
            store_id int 是  店铺ID   
            category_name string 是 分类名称  
    */
    public function addShopCategory($pid = 0, $category_id = 0, $store_id = 0, $category_name = '')
    {
        $JddjCategorySvc = new JddjCategorySvc();

        $data = $JddjCategorySvc->addShopCategory($pid, $category_name);
        $res = $JddjCategorySvc->sendAddShopCategory($data);
        $res = json_decode($res, true);

        if($res['code'] === '0'){
            $other_category = json_decode($res['result'],true);
            $other_category_id = $other_category['id'];
            $other_category_name = $category_name;
            $addCategory = addChannelCategoryInfo($this->chnId, $store_id, $category_id, $other_category_id, $other_category_name, $sequence);

            return $addCategory;
        }else{
            $res = array(
                "errNo" => "2002",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        修改商品分类
        params
            other_category_id    int  是   店铺ID   
            other_category_name  string 是 店铺分类名称
    */
    public function updateShopCategory($other_category_id = '', $other_category_name = '')
    {
        $JddjCategorySvc = new JddjCategorySvc();

        $data = $JddjCategorySvc->updateShopCategory($other_category_id, $other_category_name);
        $res = $JddjCategorySvc->sendUpdateShopCategory($data);
        $res = json_decode($res, true);

        if($res['code'] === '0'){
            $save = updateChannelCategoryInfo($other_category_id, $other_category_name, $sequence);

            return $save;
        }else{
            $res = array(
                "errNo" => "2003",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        删除商品分类
        params
            store_id    int  是   店铺ID   
            other_category_id   int  是   药品分类ID  
    */
    public function delShopCategory($store_id = 0, $other_category_id = 0)
    {
        $JddjCategorySvc = new JddjCategorySvc();

        $data = $JddjCategorySvc->delShopCategory($other_category_id);
        $res = $JddjCategorySvc->sendDelShopCategory($data);
        $res = json_decode($res, true);

        if($res['code'] === '0'){
            $del = delChannelCategoryInfo($this->chnId, $store_id, $other_category_id);

            return $del;
        }else{
            $res = array(
                "errNo" => "2005",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        查询药品分类列表
        params
            app_poi_code    string  是   店铺ID   
    */
    public function medicineCatList($app_poi_code = '')
    {
        $MtCategorySvc = new MtCategorySvc();

        $data = $MtCategorySvc->medicineCatList($app_poi_code);
        $res = $MtCategorySvc->sendMedicineCatList($data);

        if(empty($res['data']) == false){
            return $res['data'];
        }else{
            $res = array(
                "errNo" => "2004",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        添加商品信息
        params
            store_id 店铺id
            product_id 快方商品id
            other_category_id 第三方分类id
    */
    public function addSku($store_id = 0, $product_id = 0, $other_category_id = 0)
    {
        $productInfo = getProductInfoById($product_id);
        $other_category = getOtherInfoByOtherCategoryId($other_category_id);

        if(empty($productInfo)){
            $res = array(
                "errNo" => "3001"
            );

            return $res;
        }

        $outSkuId = $product_id;
        $brandId = 14152;
        $skuName = $productInfo['Caption'].$productInfo['ModeSize'];
        $skuPrice = intval($productInfo['LSJG']*100);
        $weight = 0.005;
        $images = $productInfo['Pic1'];
        $fixedStatus = 1;
        $isSale = true;
        
        $JddjProductSvc = new JddjProductSvc();

        $data = $JddjProductSvc->addSku($outSkuId, $other_category_id, $brandId, $skuName, $skuPrice, $weight, $images, $fixedStatus, $isSale);
        
        $res = $JddjProductSvc->sendAddSku($data);
        $res = json_decode($res, true);
        if($res['code'] === '0'){
            $other_product = json_decode($res['result'],true);
            $other_product_id = $other_product['skuId'];
            $add = addChannelProductInfo($this->chnId, $store_id, $product_id, $other_category_id, $other_product_id, $skuPrice, $thumb);

            return $add;
        }else{
            $res = array(
                "errNo" => "2010",
                "data" => $res
            );
            return $res;
        }
        
    }

    /*
        修改商品信息
        params
            store_id 店铺id
            product_id 快方商品id
    */
    public function updateMedicine($store_id = 0, $product_id = 0)
    {
        $productInfo = getProductInfoById($product_id);

        if(empty($productInfo)){
            $res = array(
                "errNo" => "3001"
            );

            return $res;
        }

        $app_poi_code = $store_id;
        $app_medicine_code = $product_id;
        $upc = $productInfo['BarCode'];
        $medicine_no = $productInfo['AppNum'];
        $spec = $productInfo['ModeSize'];
        $price = intval($productInfo['LSJG'] * 100);
        $stock = 0;
        $category_code = $other_category_id;
        $category_name = $other_category_name;
        $is_sold_out = 1;
        
        $MtProductSvc = new MtProductSvc();

        $data = $MtProductSvc->updateMedicine($app_poi_code, $app_medicine_code, $upc, $medicine_no, $spec, $price, $stock, $category_code, $category_name, $is_sold_out);
        
        $res = $MtProductSvc->sendUpdateMedicine($data);

        if($res['errno'] == "0"){
            // $other_product_id = $res['data']['sku_id'];
            // $add = addChannelProductInfo($this->chnId, $store_id, $product_id, $other_category_id, $other_product_id, $sale_price, $thumb);

            // sleep(2);
            // $bind = $BaiDuProductSvc->bindCategory($store_id, $other_product_id, $other_category_id);
            //  $BaiDuProductSvc->sendBindCategory($bind);

            // return $add;
        }else{
            $res = array(
                "errNo" => "2010",
                "data" => $res
            );
            return $res;
        }
        
    }

    /*
        批量创建药品
        params
            store_id 店铺id
            product_ids 商品ID列表 1,2,3
    */
    public function batchSaveMedicine($store_id = 0, $product_ids = '')
    {
        $product_ids_arr = explode(',', $product_ids);

        $productInfo = array();
        foreach ($product_ids_arr as $key => $val) {
            $productInfo[] = getProductInfoById($val);
        }

        if(empty($productInfo)){
            $res = array(
                "errNo" => "3001"
            );

            return $res;
        }

        $medicine_data = array();
        foreach ($productInfo as $key => $val) {
            $medicine_data[$key]['app_medicine_code'] = $val['ID'];
            $medicine_data[$key]['app_poi_code'] = $store_id;
            $medicine_data[$key]['upc'] = $val['BarCode'];
            $medicine_data[$key]['medicine_no'] = $val['AppNum'];
            $medicine_data[$key]['spec'] = $val['ModeSize'];
            $medicine_data[$key]['price'] = intval($val['LSJG']*100);
            $medicine_data[$key]['stock'] = 0;
            $medicine_data[$key]['category_code'] = $val['AppClass'];
            $medicine_data[$key]['category_name'] = $GLOBALS['defaultCategory'][$val['AppClass']];
            $medicine_data[$key]['is_sold_out'] = 1;
        }
        // var_dump($medicine_data);die;
        $medicine_data = json_encode($medicine_data);
        
        $MtProductSvc = new MtProductSvc();

        $data = $MtProductSvc->batchSaveMedicine($store_id, $medicine_data);
        
        $res = $MtProductSvc->sendBatchSaveMedicine($data);
        var_dump($res);die;

        if($res['data'] == "ok"){
            // $add = addChannelProductInfo($this->chnId, $store_id, $product_id, $other_category_id, $other_product_id, $sale_price, $thumb);

            // sleep(2);
            // $bind = $BaiDuProductSvc->bindCategory($store_id, $other_product_id, $other_category_id);
            //  $BaiDuProductSvc->sendBindCategory($bind);

            // return $add;
        }else{
            $res = array(
                "errNo" => "2010",
                "data" => $res
            );
            return $res;
        }
        
    }

    /*
        删除商品
        params
            app_poi_code    string  是   店铺ID   
            app_medicine_code   string  是   药品ID  
    */
    public function deleteMedicine($app_poi_code = '', $app_medicine_code = '')
    {
        $MtProductSvc = new MtProductSvc();

        $data = $MtProductSvc->deleteMedicine($app_poi_code, $app_medicine_code);
        $res = $MtProductSvc->sendDeleteMedicine($data);
        // var_dump($res);die;
        if($res['data'] == "ok"){
            $ChannelProductModel = new ChannelProductModel();

            $res = $ChannelProductModel->clearChannelProduct($this->chnId, $app_poi_code, $app_medicine_code);

            $result = $ChannelProductModel->clearChannelProductThumb($this->chnId, $app_poi_code, $app_medicine_code);

            return $res;
        }else{
            $res = array(
                "errNo" => "2013",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        查询门店药品列表 同步到本地
        params
            app_poi_code    string  是   店铺ID   
    */
    public function medicineList($app_poi_code = '')
    {
        $MtProductSvc = new MtProductSvc();

        $data = $MtProductSvc->medicineList($app_poi_code);
        $res = $MtProductSvc->sendMedicineList($data);

        if(empty($res['data']) == false){
            $productId = getProdcutIdByUPC($val['upc']);

            $ChannelProductModel = new ChannelProductModel();

            foreach ($res['data'] as $key => $val) {
                $res = replaceChannelProductInfo($this->chnId, $app_poi_code, $productId, $val['category_code'], $val['app_medicine_code'], $val['price'], $val['stock'], $val['is_sold_out']);
            }

            return $res;
        }else{

            return false;
        }
    }

    /*
        同步商品库存信息
        params
            data 商品库存信息
    */
    public function syncStock($data = array())
    {
        $other_shop_id = array();
        $new_data = array();

        foreach ($data as $key => $value) {
            $other_shop_id = getOtherShopIdByRedis($this->chnId, $value['store_id']);

            $new_data[$other_shop_id][] = $value;

        }

        $Dao = M("kfsy_channel_store.kf_channel_product");
        $Dao->startTrans();
        
        foreach ($new_data as $key => $value) {

            foreach ($value as $k => $v) {
                $updateStock = updateChannelProductStock($this->chnId, $v['store_id'], $v['other_product_id'], array('product_stock' => $v['product_stock']));

                if($updateStock === false){
                    $Dao->rollback();
                    unset($value[$k]);
                    continue;
                }
            }
            
            $postData = array();
            foreach ($value as $k1 => $v1) {
                $postData[$k1]['outSkuId'] = $v1['other_product_id']; //第三方商品ID
                $postData[$k1]['stockQty'] = $v1['product_stock']; //商品库存
            }

            $userPin = '快方送药';
            $res = $this->updateStockBatch($key, $userPin, $postData);

            if($res['code'] == '0'){
                $result = $Dao->commit();
            }else
            {
               $result = $Dao->rollback();
               return false; 
            }

        }
            
        return true;
    }

    /*
        批量同步库存信息
        params
            other_shop_id 第三方店铺ID
            userPin 操作人
            skuStockList 商品信息，最多50条
    */
    public function updateStockBatch($other_shop_id = 0, $userPin = '', $skuStockList = array())
    {
        $JddjProductSvc = new JddjProductSvc();

        $data = $JddjProductSvc->batchUpdateCurrentQtys($other_shop_id, $userPin, $skuStockList);

        $res = $JddjProductSvc->sendBatchUpdateCurrentQtys($data);

        return $res;
    }

    /*
        同步商品价格信息
        params
            data 商品价格信息
    */
    public function syncPrice($data = array())
    {
        // $data = array(
        //     array(
        //          'store_id' => 3,   
        //          'other_product_id' => 201923123,
        //          'product_price' => 2500   
        //     ),
        //     array(
        //          'store_id' => 3,   
        //          'other_product_id' => 1,
        //          'product_price' => 2500   
        //     ),
        // );

        $other_shop_id = array();
        $new_data = array();

        foreach ($data as $key => $value) {
            $other_shop_id = getOtherShopIdByRedis($this->chnId, $value['store_id']);

            $new_data[$other_shop_id][] = $value;

        }

        $Dao = M("kfsy_channel_store.kf_channel_product");
        $Dao->startTrans();
        
        foreach ($new_data as $key => $value) {

            foreach ($value as $k => $v) {
                $updatePrice = updateChannelProductPrice($this->chnId, $v['store_id'], $v['other_product_id'], array('product_price' => $v['product_price']));

                if($updatePrice === false){
                    $Dao->rollback();
                    unset($value[$k]);
                    continue;
                }
            }
            
            $postData = array();
            foreach ($value as $k1 => $v1) {
                $postData[$k1]['outSkuId'] = strval($v1['other_product_id']); //第三方商品ID
                $postData[$k1]['price'] = $v1['product_price']; //商品价格
            }

            $res = $this->updatePriceBatch($key, $postData);

            if($res['code'] == '0'){
                $result = $Dao->commit();
                // var_dump($res);
                // var_dump('success');
                // die;
            }else
            {
               $result = $Dao->rollback();
                // var_dump($res);
                // var_dump('error');
                // die;
               return false; 
            }

        }
            
        return true;
    }

    /*
        批量同步价格信息
        params
            other_shop_id 第三方店铺ID
            skuPriceInfoList 商品价格信息，最多50条
    */
    public function updatePriceBatch($other_shop_id = 0, $skuPriceInfoList = array())
    {
        $JddjProductSvc = new JddjProductSvc();

        $data = $JddjProductSvc->batchUpdateStationPrice($other_shop_id, $skuPriceInfoList);

        $res = $JddjProductSvc->sendBatchUpdateStationPrice($data);

        return $res;
    }

}
?>